package com.anti.commom.core.utils;

import org.apache.commons.beanutils.PropertyUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description TODO
 * @Author anTi
 * @Date 2020-11-27
 */
public class CookieUtils {
    private static String basedomain = null;
    private static boolean isHttpOnlySupportChecked = false;
    private static boolean isHttpOnlySupport = false;

    public CookieUtils() {
    }

    public void setBasedomain(String basedomain) {
        CookieUtils.basedomain = basedomain;
    }

    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        if (StringUtils.isNotBlank(basedomain)) {
            cookie.setDomain(basedomain);
        }

        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        if (!isHttpOnlySupportChecked) {
            isHttpOnlySupport = PropertyUtils.isWriteable(cookie, "httpOnly");
            isHttpOnlySupportChecked = true;
        }

        if (isHttpOnlySupport) {
            cookie.setHttpOnly(true);
        }

        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String name, String value) {
        addCookie(response, name, value, 1200);
    }

    public static void addCookieLongTime(HttpServletResponse response, String name, String value) {
        addCookie(response, name, value, 2592000);
    }

    public static void removeCookie(HttpServletResponse response, String name) {
        addCookie(response, name, "", 0);
    }

    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            Cookie[] arr$ = cookies;
            int len$ = cookies.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                Cookie cookie = arr$[i$];
                if (name.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }

        return null;
    }

    public static String getCookieValueByName(HttpServletRequest request, String name) {
        Cookie cookie = getCookieByName(request, name);
        return cookie == null ? null : cookie.getValue();
    }
}
